package com.giibpt;

import java.util.ArrayList;

import com.giibpt.model.HibernateUtil;
import com.giibpt.model.entities.Categoria;
import com.giibpt.model.entities.Etiqueta;
import com.giibpt.model.entities.Visitante;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.Component;
import com.vaadin.ui.DefaultFieldFactory;
import com.vaadin.ui.Field;
import com.vaadin.ui.Form;
import com.vaadin.ui.FormFieldFactory;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Panel;
import com.vaadin.ui.Table;
import com.vaadin.ui.Table.ColumnGenerator;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;

public class MttoUsuarios extends Panel{
	private TextField txtSearch;
	private Button btnSearch;
	private Button btnCancel;
	private Button btnNew;
	private Button btnSave;
	
	private Table tblResult;
	private VerticalLayout lytSearch;
	private VerticalLayout lytEdit;
	private BeanItemContainer<Visitante> container;
	private Form form;
	
	private TextField txtEtiqueta;
	
	private int mode;
	
	public MttoUsuarios() {
		txtSearch = new TextField("");
		txtSearch.setInputPrompt("Digite el nombre del usuario");
		btnSearch = new Button("Buscar");
		btnSearch.addListener(new Button.ClickListener() {
			
			public void buttonClick(ClickEvent event) {
				search();
			}
		});
		
		btnNew = new Button("Nuevo");
		btnNew.addListener(new Button.ClickListener() {
			
			public void buttonClick(ClickEvent event) {
				newEntity();
			}
		});
		
		btnCancel = new Button("Volver");
		btnCancel.addListener(new Button.ClickListener() {
			
			public void buttonClick(ClickEvent event) {
				cancelEntity();
			}
		});
		
		btnSave = new Button("Guardar");
		btnSave.addListener(new Button.ClickListener() {
			
			public void buttonClick(ClickEvent event) {
				saveEntity();
			}
		});
		
		
		HorizontalLayout lytSearchSection = new HorizontalLayout();
		lytSearchSection.addComponent(txtSearch);
		lytSearchSection.addComponent(btnSearch);
		lytSearchSection.setWidth("100%");
		
		container = new BeanItemContainer(Visitante.class); 
		tblResult = new Table();
		tblResult.setContainerDataSource(container);
		tblResult.setImmediate(true);
		tblResult.setSelectable(true);
		tblResult.setMultiSelect(false);
		tblResult.setVisibleColumns(new Object[]{"idVisitante", "nombre", "categoria", "etiqueta"});
		tblResult.addGeneratedColumn("etiqueta", new ColumnGenerator() {
			
			public Component generateCell(Table source, Object itemId, Object columnId) {
				Visitante visitante = (Visitante) itemId;
				return new Label(visitante.getEtiqueta().getIdEtiqueta());
			}
		});
		tblResult.addListener(new Property.ValueChangeListener() {
			
			public void valueChange(ValueChangeEvent event) {
				editEntity();
			}
		});
		

		lytSearch = new VerticalLayout();
		lytSearch.addComponent(lytSearchSection);
		lytSearch.addComponent(tblResult);
		lytSearch.addComponent(btnNew);
		
		HorizontalLayout lytEditPanel = new HorizontalLayout();
		lytEditPanel.addComponent(btnSave);
		lytEditPanel.addComponent(btnCancel);
		
		txtEtiqueta = new TextField("Etiqueta");
		txtEtiqueta.setRequired(true);
		txtEtiqueta.setNullRepresentation("");
		form = new Form();
		form.setVisibleItemProperties(new Object[]{"idVisitante", "nombre", "categoria"});
		
		form.setFormFieldFactory(new FormFieldFactory() {
			DefaultFieldFactory factory = DefaultFieldFactory.get();
			public Field createField(Item item, Object propertyId, Component uiContext) {
				Field field;
				if("categoria".equals(propertyId)){
					ComboBox categoria = new ComboBox("Categoria", HibernateUtil.list(Categoria.class));
					categoria.setNullSelectionAllowed(false);
					field = categoria;
				}else{
					field = factory.createField(item, propertyId, uiContext);
				}
				if(field instanceof TextField){
					((TextField) field).setNullRepresentation("");
				}
				field.setRequired(true);
				return field; 
			}
		});
		lytEdit = new VerticalLayout();
		lytEdit.addComponent(form);
		lytEdit.addComponent(lytEditPanel);
		
		VerticalLayout lytMain = new VerticalLayout();
		lytMain.addComponent(lytSearch);
		
		setContent(lytMain);
		
		
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void search(){
		container.removeAllItems();
		container.addAll(new ArrayList(HibernateUtil.getVisitantes((String)txtSearch.getValue()))); 
	}
	
	private void newEntity(){
		mode = 1;
		txtEtiqueta.setValue(null);
		form.setValue(new Visitante());
		form.addField("etiqueta", txtEtiqueta);
		getContent().removeAllComponents();
		getContent().addComponent(lytEdit);
		
	}
	
	private void editEntity(){
		mode = 2;
		Visitante visitante = (Visitante) tblResult.getValue();
		if(visitante == null){
			return;
		}
		form.setValue(tblResult.getValue());
		form.addField("etiqueta", txtEtiqueta);
		form.getItemProperty("idVisitante").setReadOnly(true);
		txtEtiqueta.setValue(visitante.getEtiqueta().getIdEtiqueta()); 
		getContent().removeAllComponents();
		getContent().addComponent(lytEdit);
		
	}
	
	private void saveEntity(){
		if(form.isValid()){
			form.commit();
			Visitante visitante = (Visitante) form.getValue();
			visitante.setEtiqueta(new Etiqueta());
			visitante.getEtiqueta().setIdEtiqueta((String) txtEtiqueta.getValue());
			if(mode == 1){
				if(HibernateUtil.get(Visitante.class, visitante.getIdVisitante()) != null){
					getWindow().showNotification("Ya existe un visitante con ese codigo");
					return;
				}
				if(HibernateUtil.get(Etiqueta.class, visitante.getEtiqueta().getIdEtiqueta()) != null){
					getWindow().showNotification("Ya existe un visitante con el codigo de etiqueta establecido");
					return;
				}
				HibernateUtil.save(form.getValue());
				tblResult.addItem(visitante);
			}else{
				Etiqueta etiqueta = (Etiqueta) HibernateUtil.get(Etiqueta.class, visitante.getEtiqueta().getIdEtiqueta());
				if(etiqueta != null 
						&& etiqueta.getVisitante() != null
						&& !visitante.getIdVisitante().equals(etiqueta.getVisitante().getIdVisitante())){
					getWindow().showNotification("Ya existe un visitante con el codigo de etiqueta establecido");
					return;
				}
				tblResult.removeItem(visitante);
				tblResult.addItem(visitante);
				HibernateUtil.update(form.getValue());
			}
			
			getContent().removeAllComponents();
			getContent().addComponent(lytSearch);
			getWindow().showNotification("registro almacenado satisfactoriamente");
			
		}else{
			getWindow().showNotification("Todos los campos son obligatorios");
		}
	}
	
	private void cancelEntity(){
		getContent().removeAllComponents();
		getContent().addComponent(lytSearch);
	}
	

}
